// 商户中心>运营商
import React, { useState, useEffect } from 'react'
import { Row, Col, Form, Input, Button, Select, Table, Modal, message } from 'antd'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import { getAddressList, getCameraList, macAdressAction, getSupplierList, deleteMacAdress } from '@/services/dataCenter/macAddress'
import RenderButtom from '@/components/RenderButton'
import SearchBox from '@/components/SearchBox'
import { connect } from 'dva'
import EditorForm from './subComp/EditorForm'
import AddForm from './subComp/AddForm'


const columns = [
  {
    title: '所属门店',
    dataIndex: 'storeName',
    key: 'storeName'
  },
  {
    title: 'MAC名称',
    dataIndex: 'macName',
    key: 'macName',
  },
  {
    title: 'MAC地址',
    dataIndex: 'macAddress',
    key: 'macAddress',
  }
];

const MacConfig = props => {
  const { form, merchants, stores, dispatch } = props
  const { getFieldDecorator } = form
  const [addressList, setAddressList] = useState([])
  const [total, setTotalPage] = useState(null)
  const [record, setRecord] = useState(null)
  const [visible, setVisible] = useState(false)
  const [confirmLoading, setConfirmLoading] = useState(false)
  const [cameraList, setCameraList] = useState(null)
  const [isEdit, setIsEdit] = useState(false)


  const [param, setParam] = useState({
    pageNo: 1,
    pageSize: 10,
    name: "",
    storeId: "",
    supplierId: ""
  })

  const addFormParam = {
    storeId: "",
    supplierId: "",
    macAddress: "",
    macName: "",
  }

  useEffect(() => {
    init()
    dispatch({
      type: 'dataCenter/fetchMerchants'
    })
  }, [])
  const init = async (param) => {
    const r_1 = await getAddressList(param)
    setAddressList(r_1.data)
    setTotalPage(r_1.total)

    const r_2 = await getCameraList()
    if (r_2.code == 0 && r_2.data) {
      setCameraList(r_2.data.cameraList)
    }

  }

  const handleMacAdress = (val) => {
    console.log(val)
  }

  const handleSelct = (macAddress, deviceName) => {
    console.log(macAddress, deviceName)
    setRecord({
      ...record,
      macAddress,
      macName: deviceName
    })
  }

  const pagination = {
    total: parseInt(total),
    onChange (page) {
      init({
        ...param,
        pageNo: page,
      })
    }
  }
  // 按钮处理
  const handleBtn = type => {
    switch (type) {
      case 1:
        setIsEdit(false)
        setVisible(true)
        break;
      case 3:
        if (record && record[0].id) {
          setIsEdit(true)
          setVisible(true)
        } else {
          message.warning('必须先选中一条数据再编辑')
        }
        break;

      case 4:
        if (record && record[0].id) {
          deleteMacAdress({id: record[0].id}).then(res => {
            message.warning(res.msg)
            init()
          })
        } else {
          message.success('必须先选中一条数据再点击删除')
        }
        break;

      default:
        break;
    }
  }

  const handleOk = (e) => {
    setConfirmLoading(true)
    let storeFaceGuest = {}
    if (isEdit) {
        storeFaceGuest = {
          id: record[0].id,
          storeId: record[0].storeId,
          supplierId: record[0].supplierId,
          macName: record[0].macName,
          macAddress: record[0].macAddress
        }
    } else {
      storeFaceGuest = addFormParam
    }
    const params = {
      storeFaceGuest: storeFaceGuest
    }
    macAdressAction(params).then(res => {
      if (res.code === "0") {
        message.success('操作成功')
      } else {
        message.success(res.msg)
      }
      setConfirmLoading(false)
      setVisible(false)
      init()
    })
  }
  const handleCancel = () => {
    setVisible(false)
  }

  const rowSelection = {
    type: 'radio',
    onChange: (selectedRowKeys, selectedRows) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
      setRecord(selectedRows)
    },
  }

  // 清空查询条件
  const handleReset = () => {
    form.resetFields()
    init()
  }
  // 查询表单逻辑
  const handleSearch = e => {
    e.preventDefault()
    form.validateFields((err, values) => {
      console.log('Received values of form: ', values)
      init({
        ...values,
        pageNo: 1,
        pageSize: 10,
      })
    })
  }

  const selectMerchant = (val) => {
    dispatch({
      type: 'dataCenter/fetchStores',
      payload: {
        supplierId: val,
        pageSize: 999,
      }
    })
  }
  // 查询表单
  const getFields = () => {
    return (
      <>
        <Col span={6}>
          <Form.Item label={`所属商户`}>
            {getFieldDecorator('supplierId', {initialValue: '',})(
              <Select onChange={selectMerchant}>
                {merchants && merchants.map((r, index) => <Select.Option key={index} value={r.id}>{r.merchantName}</Select.Option>)}
              </Select>,
            )}
          </Form.Item>
        </Col>
        <Col span={6}>
          <Form.Item label={`选择门店`}>
            {getFieldDecorator(`storeId`, {initialValue: '',})
              (<Select>
                {
                  stores && stores.map(m => <Select.Option key={m.id} value={m.id}>{m.name}</Select.Option>)
                }
              </Select>)}
          </Form.Item>
        </Col>
        <Col span={6}>
          <Form.Item label={`门店名称`}>
            {getFieldDecorator(`name`, {initialValue: '',})
              (<Input />)}
          </Form.Item>
        </Col>
      </>
    )
  }

  return (<PageHeaderWrapper>
    <SearchBox handleReset={handleReset} handleSearch={handleSearch} getFields={getFields} />
    <Row>
      <RenderButtom click={handleBtn} />
    </Row>
    <Table
      columns={columns}
      dataSource={addressList}
      rowKey={record => record.id}
      pagination={pagination}
      rowSelection={rowSelection}
    />
    <Modal
      title={isEdit ? "编辑数据" : "新增数据"}
      visible={visible}
      onOk={handleOk}
      confirmLoading={confirmLoading}
      onCancel={handleCancel}
    >
      {isEdit
        ? <EditorForm handleSelct={handleSelct} handleMacAdress={handleMacAdress} record={record} cameraList={cameraList} />
        : <AddForm addFormParam={addFormParam} handleSelct={handleSelct} handleMacAdress={handleMacAdress} cameraList={cameraList} selectMerchant={selectMerchant} merchants={merchants} stores={stores} />}
    </Modal>
  </PageHeaderWrapper>)
}

export default connect(({ dataCenter }) => ({
  merchants: dataCenter.merchants,
  stores: dataCenter.stores,
}))(Form.create()(MacConfig))
